package net.xujialiang.XTestRPA.Controller.EnvManager;

import com.google.gson.Gson;
import net.xujialiang.XTestRPA.Config.SpringSecurityConfig.SecurityUser;
import net.xujialiang.XTestRPA.Entity.Env.XRPAEnv;
import net.xujialiang.XTestRPA.Entity.Env.XRPAEnvTag;
import net.xujialiang.XTestRPA.Model.ResultData;
import net.xujialiang.XTestRPA.Service.Env.XRPAEnvService;
import net.xujialiang.XTestRPA.Service.Env.XRPAEnvTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import static net.xujialiang.XTestRPA.Enum.ReturnCode.RC999;

@RequestMapping("/api/env")
@RestController
public class EnvMgr {

    @Autowired
    XRPAEnvService envService;
    @Autowired
    XRPAEnvTagService tagService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ResultData create(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String createAccount = sUser.getUsername();
        String ttc = sUser.getTTC();
        try {
            envService.createEnv(reqBody, createAccount, ttc);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResultData delete(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        Integer id = (Integer) reqBody.get("id");
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            envService.deleteEnv(id, ttc);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    /**
     * 支持根据标签、分组筛选
     * @param reqBody
     * @param request
     * @param auth
     * @return
     */
    @RequestMapping(value = "/fetch", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<Map<String, Object>> fetch(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        Integer page = (Integer) reqBody.get("page");
        Integer pageSize = (Integer) reqBody.get("pageSize");
        String groupId = (String) reqBody.getOrDefault("groupId", "");
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        List<String> tagIds = (List<String>) reqBody.getOrDefault("tagIds", new ArrayList<>());
        String envName = (String) reqBody.get("envName");
        try {
            Map<String, Object> ret = envService.fetchByPage(groupId, envName, tagIds, ttc, page, pageSize);
            return ResultData.success(ret);
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    /**
     * 支持根据标签、分组筛选
     * @param reqBody
     * @param request
     * @param auth
     * @return
     */
    @RequestMapping(value = "/fetchById", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<XRPAEnv> fetchById(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        Integer id = (Integer) reqBody.get("id");
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            XRPAEnv ret = envService.fetchById(id, ttc);
            return ResultData.success(ret);
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/fetchByEnvID", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<XRPAEnv> fetchByEnvID(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        String envID = (String) reqBody.get("envID");
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            XRPAEnv ret = envService.fetchByEnvID(envID, ttc);
            return ResultData.success(ret);
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/order", method = RequestMethod.POST)
    @ResponseBody
    public ResultData order(@RequestBody Map<Integer, Integer> reqBody, HttpServletRequest request, Authentication auth) {
        try {
            SecurityUser sUser = (SecurityUser) auth.getPrincipal();
            String ttc = sUser.getTTC();
            envService.updateEnvOrder(reqBody, ttc);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResultData update(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            envService.update(reqBody, ttc);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ResponseBody
    public ResultData exportEnv(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, HttpServletResponse response, Authentication auth) {
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            List<XRPAEnv> envs= envService.exportData(reqBody, ttc);
            // 导出标签
            HashSet<String> tagIds = new HashSet();
            for (XRPAEnv env:envs) {
                if(env.getTagIDs()!=null && env.getTagIDs().length()>0){
                    String[] ids = env.getTagIDs().split(",");
                    for (String id : ids) {
                        tagIds.add(id);
                    }
                }
            }
            List<XRPAEnvTag> tags = tagService.fetchTagByTagIds(new ArrayList<>(tagIds));
            for (XRPAEnvTag tag: tags) {
                tag.setId(null);
            }
            HashMap<String, Object> ret = new HashMap<String, Object>();
            ret.put("EnvList", envs);
            ret.put("Tags", tags);
            return ResultData.success(ret);
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public ResultData importEnv(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile,  @RequestParam("groupID") String groupID, Authentication auth) {
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        try {
            // 1. 导入标签
            tagService.importTags(multipartFile, ttc);
            // 2. 导入环境
            envService.importData(multipartFile, groupID, ttc);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }
}
